﻿using System;
using DBProvider.Providers;
using System.Linq;

namespace HealthCommunity.Controls
{
	public partial class UCActivityDetail : System.Web.UI.UserControl
	{
		private IActivityProvider _ActivityProvider;

		public int CurrentActivityID
		{
			get
			{
				return CommonHelper.QueryStringInt("activityid");
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				BindActivity();
			}
		}

		protected void btnSign_Click(object sender, EventArgs e)
		{
			var user = SiteContext.Current.CurrentUser;

			if(user != null && CurrentActivityID > 0)
			{
				var rltActivityAndUser = new DBProvider.RLT_ACTIVITYANDUSER() { ActivityID = CurrentActivityID, userID = user.UserID };

				if(_ActivityProvider == null)
				{
					_ActivityProvider = new DBProvider.Providers.ActivityProvider();
				}

				if(_ActivityProvider.CreateRLTActivityAndUser(rltActivityAndUser))
				{
					BindActivity();
				}
			}
		}

		private void BindActivity()
		{
			if(CurrentActivityID > 0)
			{
				_ActivityProvider = new ActivityProvider();

				var theActivity = _ActivityProvider.GetActivity(CurrentActivityID);

				if(theActivity != null)
				{
					this.ltrActivityAddress.Text = theActivity.ActivityAddress;
					this.ltrActivityCategory.Text = theActivity.ActivityCategory != null ? theActivity.ActivityCategory.ActivityCategoryName : string.Empty;
					this.ltrActivityContactPerson.Text = theActivity.ActivityContactPerson;
					this.ltrActivityContactTel.Text = theActivity.ActivityContactTel;
					//this.ltrActivityCreator.Text = string.Empty;
					this.ltrActivityDescription.Text = theActivity.ActivityDescription;
					this.ltrActivityStartTime.Text = theActivity.ActivityStartTime.GetValueOrDefault().ToString();
					this.ltrActivityTitle.Text = theActivity.ActivityTitle;
					this.ltrDeadlineTime.Text = theActivity.DeadlineTime.GetValueOrDefault().ToString();
					this.ltrMaximumPerson.Text = theActivity.MaximumPerson.ToString();
					if(theActivity.User != null)
					{
						this.ltrActivityCreator.Text = theActivity.User.UserName;
					}
					if(theActivity.RLT_ACTIVITYANDUSERs != null && theActivity.RLT_ACTIVITYANDUSERs.Count > 0)
					{
						ltrSignedPersons.Text = "已报名人数: " + theActivity.RLT_ACTIVITYANDUSERs.Count.ToString();

						var user = SiteContext.Current.CurrentUser;
						if(user != null)
						{
							btnSign.Enabled = !(theActivity.RLT_ACTIVITYANDUSERs.Select(au => au.userID).Contains(user.UserID));
						}
					}
					else
					{
						ltrSignedPersons.Text = "已报名人数: 0";
					}
				}
			}
		}
	}
}